package com.ugoodtech.mdcc.client.controller;
        /* Copyright (C) Ugoodtech, Inc - All Rights Reserved
         * Unauthorized copying of this file, via any medium is strictly prohibited
         * Proprietary and confidential
         * Written by Stone Shaw, 15/11/19
         */


import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.domain.Station;
import com.ugoodtech.mdcc.core.domain.User;
import com.ugoodtech.mdcc.core.repository.StationRepository;
import com.ugoodtech.mdcc.core.repository.UserRepository;
import com.ugoodtech.mdcc.core.utils.AliServiceUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.security.Principal;
import java.util.UUID;

@Api(description = "OSS上传文件")
@Controller
@RequestMapping("/oss")
public class OssController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(OssController.class);

    @Autowired
    private StationRepository stationRepository;

    @Autowired
    private UserRepository userRepository;

    @Value("${oss.bucket.name}")
    private String ossBucketName;
    @Value("${oss.photo.bucket.name}")
    private String ossPhotoBucketName;

    @ApiOperation("上传文件")
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse uploadFile(
            @ApiParam("文件数据") @RequestParam(value = "file") MultipartFile multfile
    ) throws Exception {
//        isSystemUserLogin();
        String fileName = multfile.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 用uuid作为文件名，防止生成的临时文件重复
        final File excelFile = File.createTempFile(String.valueOf(UUID.randomUUID()), prefix);
        // MultipartFile to File
        multfile.transferTo(excelFile);


        String dir = "backend/" + System.currentTimeMillis();
        AliServiceUtil.putFile(excelFile, dir, ossBucketName);
        if (excelFile.exists()) {
            excelFile.delete();
        }
        return JsonResponse.successResponseWithData(dir);
    }

    public static String getFileNameWithoutSuffix(String name) {
        return name.substring(0, name.lastIndexOf("."));
    }


    @ApiOperation("上传图片")
    @RequestMapping(value = "/uploadPhoto", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse uploadPhoto(
            Principal principal,
            @ApiParam("图片文件数据") @RequestParam(value = "file") MultipartFile file,
            @ApiParam("报告类型") @RequestParam(value = "reportPath", required = false) String reportPath,
            @ApiParam("维修站ID") @RequestParam(value = "stationId", required = false) Long stationId,
            @ApiParam("问题ID") @RequestParam(value = "questionId", required = false) String questionId
    ) throws Exception {
        /**
         * **********************************************
         * 新加参数 用于划分每个维修站的照片
         */
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("500", "未找到此用户");
        }
        logger.info("**********************************************");
        logger.info("<<<<<<<<<开始上传照片>>>>>>>>>>");
        logger.info("<<<<<<<<<上传照片用户ID为：" + clientUser.getId() + ">>>>>>>>>>");
        logger.info("<<<<<<<<<上传的维修站ID为：" + stationId + ">>>>>>>>>>");
        logger.info("<<<<<<<<<上传的问题ID为：" + questionId + ">>>>>>>>>>");
        if (stationId != null && stationId != 0) {
            Station station = stationRepository.findOne(stationId);
            if (station == null) {
                return JsonResponse.errorResponseWithError("抱歉", "未找到该维修站");
            }
        }
        String path = "";
        if (StringUtils.isNotEmpty(reportPath)) {
            if (reportPath.equals(Constants.OSS_SERVICE)) {
                path = "backend/stations/" + stationId + "/" + Constants.OSS_SERVICE + "/";
            }
            if (reportPath.equals(Constants.OSS_COLOR)) {
                path = "backend/stations/" + Constants.OSS_COLOR + "/";
            }
            if (reportPath.equals(Constants.OSS_PAINT)) {
                path = "backend/stations/" + stationId + "/" + Constants.OSS_PAINT + "/";
            }
        }
        Long time = System.currentTimeMillis();
        String fileName = "";
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        if (StringUtils.isNotEmpty(questionId)) {
            fileName = time + "_" + questionId + "_" + suffix;
        } else {
            fileName = time + "_" + suffix;
        }
        if (fileName.indexOf(".") == -1) {
            fileName += ".jpg";
            logger.info("原文件名没有后缀");
        }
        String realPath = path + fileName;
        /**
         * **********************************************
         */

        logger.info("原始文件名" + file.getOriginalFilename());
        String dir = "backend/photo/" + time + "_" + suffix;
        if (dir.indexOf(".") == -1) {
            dir += ".jpg";
            logger.info("原文件名没有后缀");
        }
        logger.info("文件路径为" + dir);
        if (StringUtils.isNotEmpty(realPath)) {
            AliServiceUtil.putObject(file.getInputStream(), realPath, ossPhotoBucketName);
            logger.info(System.currentTimeMillis() - time + "");
            logger.info("文件路径为" + realPath);
            return JsonResponse.successResponseWithData(realPath);
        } else {
            AliServiceUtil.putObject(file.getInputStream(), dir, ossPhotoBucketName);
            logger.info(System.currentTimeMillis() - time + "");
            return JsonResponse.successResponseWithData(dir);
        }
    }


}
